<template>
  <div class="headwear-selector">
    <!-- 选择框显示 -->
    <div class="selector-display" @click="openDialog">
      <div v-if="selectedHeadwear" class="selected-item">
        <el-image :src="selectedHeadwear.imageUrl" style="width: 40px; height: 40px; margin-right: 10px" fit="cover" />
        <span>{{ selectedHeadwear.name }}</span>
        <el-tag v-if="selectedHeadwear.isRecommended" size="small" type="success" style="margin-left: 10px">推荐</el-tag>
        <el-button type="text" size="small" @click.stop="clearSelection" style="margin-left: 10px; color: #f56c6c">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div v-else class="placeholder">
        <el-icon><Plus /></el-icon>
        <span>请选择头饰</span>
      </div>
      <el-icon class="arrow-icon"><ArrowDown /></el-icon>
    </div>

    <!-- 头饰选择弹窗 -->
    <el-dialog v-model="showDialog" title="选择头饰" width="90%" :close-on-click-modal="false" class="headwear-dialog" @close="handleDialogClose" @keyup.enter="handleEnterKey">
      <!-- 搜索和筛选 -->
      <div class="filter-container">
        <el-input v-model="listQuery.name" placeholder="请输入头饰名称" style="width: 200px" class="filter-item" @keyup.enter="handleFilter" />
        <el-select v-model="listQuery.categoryId" placeholder="选择分类" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id" />
        </el-select>
        <el-select v-model="listQuery.isRecommended" placeholder="推荐状态" clearable style="width: 120px" class="filter-item">
          <el-option label="推荐" :value="true" />
          <el-option label="不推荐" :value="false" />
        </el-select>
        <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">搜索</el-button>
        <el-button class="filter-item" type="warning" icon="Refresh" @click="handleRefresh">重置</el-button>
      </div>

      <!-- 头饰列表 -->
      <div class="headwear-list">
        <el-table v-loading="listLoading" :data="headwearList" element-loading-text="Loading..." border fit highlight-current-row @row-click="handleSelectHeadwear" class="headwear-table" :row-key="_id">
          <el-table-column align="center" type="index" label="序号" width="60" />
          <el-table-column label="头饰图片" width="80" align="center">
            <template #default="scope">
              <el-image :src="scope.row.imageUrl" style="width: 60px; height: 60px" fit="cover" :z-index="99999" preview-teleported :preview-src-list="[scope.row.imageUrl]" />
            </template>
          </el-table-column>
          <el-table-column label="头饰名称" align="center" min-width="120">
            <template #default="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" width="100">
            <template #default="scope">
              {{ scope.row.categoryName }}
            </template>
          </el-table-column>
          <el-table-column label="推荐状态" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isRecommended ? 'success' : 'info'">
                {{ scope.row.isRecommended ? '推荐' : '不推荐' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 空状态 -->
          <template #empty>
            <div class="empty-state">
              <el-icon size="48" color="#c0c4cc"><Warning /></el-icon>
              <p>暂无头饰数据</p>
              <p v-if="listQuery.name || listQuery.categoryId || listQuery.isRecommended !== ''" style="font-size: 12px; color: #909399">请尝试调整筛选条件</p>
            </div>
          </template>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-if="total > 0" style="margin-top: 15px; text-align: center" :page-size="listQuery.pageSize" @change="handlePageChange" background layout="prev, pager, next, total" :total="total" />
      </div>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button v-if="selectedHeadwear" type="primary" @click="confirmSelection">确定选择</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, onMounted, watch } from 'vue';
  import { getHeadwearList, getHeadwearCategories, getHeadwearDetail } from '@/api/headwear';
  import { Plus, ArrowDown, Close, Warning } from '@element-plus/icons-vue';

  const props = defineProps({
    modelValue: {
      type: String,
      default: ''
    }
  });

  const emit = defineEmits(['update:modelValue', 'change']);

  const showDialog = ref(false);
  const headwearList = ref([]);
  const categoryOptions = ref([]);
  const listLoading = ref(false);
  const total = ref(0);
  const selectedHeadwear = ref(null);

  const listQuery = ref({
    pageIndex: 1,
    pageSize: 10,
    name: '',
    categoryId: '',
    isRecommended: ''
  });

  // 监听外部传入的值变化
  watch(
    () => props.modelValue,
    newVal => {
      if (newVal && headwearList.value.length > 0) {
        selectedHeadwear.value = headwearList.value.find(item => item._id === newVal) || null;
      }
    },
    { immediate: true }
  );

  // 获取头饰列表
  const getHeadwearData = async () => {
    listLoading.value = true;
    try {
      const response = await getHeadwearList(listQuery.value);
      if (response.code === 200) {
        headwearList.value = response.data.list;
        total.value = response.data.total;

        // 如果有选中的值，找到对应的头饰
        if (props.modelValue && !selectedHeadwear.value) {
          selectedHeadwear.value = headwearList.value.find(item => item._id === props.modelValue) || null;
        }
        // 判断，如果列表中没有头饰，则可能不在第一页，加载头饰详细
        if (!selectedHeadwear.value && props.modelValue) {
          getHeadwearDetail(props.modelValue).then(res => {
            if (res.code === 200) {
              selectedHeadwear.value = res.data;
            }
          });
        }
      } else {
        console.error('获取头饰列表失败:', response.msg);
      }
    } catch (error) {
      console.error('获取头饰列表失败:', error);
    } finally {
      listLoading.value = false;
    }
  };

  // 获取分类列表
  const getCategories = async () => {
    try {
      const response = await getHeadwearCategories();
      if (response.code === 200) {
        categoryOptions.value = response.data.list;
      } else {
        console.error('获取分类列表失败:', response.msg);
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  // 搜索
  const handleFilter = () => {
    listQuery.value.pageIndex = 1;
    getHeadwearData();
  };

  // 重置
  const handleRefresh = () => {
    listQuery.value = {
      pageIndex: 1,
      pageSize: 10,
      name: '',
      categoryId: '',
      isRecommended: ''
    };
    getHeadwearData();
  };

  // 分页
  const handlePageChange = page => {
    listQuery.value.pageIndex = page;
    getHeadwearData();
  };

  // 选择头饰
  const handleSelectHeadwear = row => {
    selectedHeadwear.value = row;
  };

  // 清空选择
  const clearSelection = () => {
    selectedHeadwear.value = null;
    emit('update:modelValue', '');
    emit('change', '');
  };

  // 确认选择
  const confirmSelection = () => {
    if (selectedHeadwear.value) {
      emit('update:modelValue', selectedHeadwear.value._id);
      emit('change', selectedHeadwear.value._id);
      showDialog.value = false;
    }
  };

  // 打开弹窗
  const openDialog = () => {
    showDialog.value = true;
    getHeadwearData(); // 打开弹窗时重新获取数据
    getCategories();
  };

  // 弹窗关闭时触发
  const handleDialogClose = () => {
    // 弹窗关闭时重置筛选条件
    listQuery.value = {
      pageIndex: 1,
      pageSize: 10,
      name: '',
      categoryId: '',
      isRecommended: ''
    };
  };

  // 处理回车键
  const handleEnterKey = () => {
    if (showDialog.value) {
      confirmSelection();
    }
  };

  onMounted(() => {
    getHeadwearData();
    getCategories();
  });
</script>

<style scoped>
  .headwear-selector {
    width: 100%;
  }

  .selector-display {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #fff;
  }

  .selector-display:hover {
    border-color: #409eff;
  }

  .selected-item {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .placeholder {
    display: flex;
    align-items: center;
    color: #c0c4cc;
    flex: 1;
  }

  .placeholder .el-icon {
    margin-right: 8px;
  }

  .arrow-icon {
    color: #c0c4cc;
    transition: transform 0.3s;
  }

  .selector-display:hover .arrow-icon {
    transform: rotate(180deg);
  }

  /* 弹窗样式 */
  .headwear-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }

  .headwear-dialog :deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
    padding: 20px 20px 15px;
  }

  .headwear-dialog :deep(.el-dialog__footer) {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px 20px;
  }

  .filter-container {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .filter-item {
    margin-right: 10px;
  }

  .headwear-list {
    max-height: 400px;
    overflow-y: auto;
  }

  .headwear-table :deep(.el-table__row) {
    cursor: pointer;
  }

  .headwear-table :deep(.el-table__row:hover) {
    background-color: #f5f7fa;
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;
    color: #909399;
  }

  .empty-state p {
    margin: 10px 0 0 0;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .filter-container {
      flex-direction: column;
      align-items: stretch;
    }

    .filter-item {
      margin-right: 0;
      margin-bottom: 10px;
    }

    .headwear-dialog {
      width: 95% !important;
    }

    .selector-display {
      padding: 6px 10px;
    }

    .selected-item {
      flex-direction: column;
      align-items: flex-start;
    }

    .selected-item .el-image {
      margin-bottom: 5px;
    }
  }
</style>
